import java.util.LinkedList;
import java.util.Queue;

//迷宫中离入口最近的出口
//测试连接:https://leetcode.cn/problems/nearest-exit-from-entrance-in-maze/
public class NearestExit {
    int[] dx = { 0, 0, -1, 1 };
    int[] dy = { 1, -1, 0, 0 };

    public int nearestExit(char[][] maze, int[] e) {
        int m = maze.length, n = maze[0].length;
        boolean[][] vis = new boolean[m][n];
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] { e[0], e[1] });
        vis[e[0]][e[1]] = true;
        int step = 0;
        while (!q.isEmpty()) {
            step++;
            int sz = q.size();
            for (int i = 0; i < sz; i++) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for (int j = 0; j < 4; j++) {
                    int x = a + dx[j], y = b + dy[j];
                    if (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.'
                            && !vis[x][y]) {
                        // 判断是否已经到出⼝
                        if (x == 0 || x == m - 1 || y == 0 || y == n - 1)
                            return step;
                        vis[x][y] = true;
                        q.add(new int[] { x, y });
                    }
                }
            }
        }
        return -1;
    }
}
